package com.jml.juc.forkjoinpool;

/**
 * @Author: J
 * @DATE: 2022-04-27 16:17
 */

import java.util.concurrent.RecursiveTask;

/**
 * RecursiveTask 递归地拆分和执行任务，有返回值
 */
class ForkJoinSumCalculate extends RecursiveTask<Long> {

    /**
     *
     */
    private static final long serialVersionUID = -259195479995561737L;

    private long start;
    private long end;

    private static final long THURSHOLD = 10000L;  //临界值，任务拆分到多少不再拆分

    public ForkJoinSumCalculate(long start, long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        long length = end - start;
        if (length <= THURSHOLD) {
            long sum = 0L;
            for (long i = start; i <= end; i++) {
                sum += i;
            }
            return sum;
        } else {
            long middle = (start + end) / 2;
            ForkJoinSumCalculate left = new ForkJoinSumCalculate(start, middle);
            left.fork(); //进行拆分，同时压入线程队列
            ForkJoinSumCalculate right = new ForkJoinSumCalculate(middle + 1, end);
            right.fork(); //
            return left.join() + right.join();//将拆分后额结果合并
        }
    }

}
